<?php


namespace app\api\controller\v27;


use app\api\controller\v2\Auth;
use app\common\cachemodel\Goods as GoodsCacheModel;
use app\common\cachemodel\live\LiveGoodsActivity;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeCreateNameRecord;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeRecord;
use app\common\cachemodel\Recode;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\zl6\Zl6Meditation;
use app\common\cachemodel\ZlcrCustomReportGoods;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use Exception;
use think\Env;

/**
 * @version 2.7.0
 * Class Goods
 * @package app\api\controller\v22
 */
class Goods extends Auth
{
    protected $notice = [
        1 => '以下所有时间均为东八区哦',
        2 => '下单前请务必核对好购买信息',
    ];

    protected $gidDefault = [
        1 => 1,
        2 => 2,
        3 => 20,
        4 => 24,
        5 => 19,
        8 => 35,
        28 => 0,
        29 => 144,
        30 => 145,
        31 => 148,
        32 => 159,
        34 => 160,
    ];

    protected $pay_pop_tips = "本服务由准了APP提供，购买该服务以下服务声明须知：\n\n1、本服务由准了官方平台分发至平台专业占星师，由于服务含有为付费者定做、定制属性，超出规定时间将扣除相应费用，不支持无理由取消订单退款\n\n2、因本服务有定制特殊性，下单后派发队列中未被占星师接单可取消订单，如已派发被占星师接单，15分钟内取消订单退款订单金额的90%，收取10%的订单服务费用，如超过15分钟取消订单退款订单金额的10%，平台将收取90%的服务费，请慎重取消。如已完成服务，则不可申请退款\n\n3、本报告内容由占星师结合提问者星盘定制产出，因测算维度技法不同，内容理性判断仅供参考，请勿过于依赖，事件的改善走向都由提问者本身判断决定";

    /**
     * 获取商品信息
     * @throws Exception
     */
    public function read()
    {
        $type = input('param.type/d', 0);
        if (!$type)
        {
            return show(config('code.error'), '未知的商品');
        }
        $gid = input('param.gid/d', 0);
        $rid = input('param.rid/d', 0);
        $rid2 = input('param.rid2/d', 0);
        $start_time = input('param.start_time/s', '');
        $liveId = input('live_id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);
        $param = input('param.param', '');
        $param_info = $param ? json_decode($param, true) : '';
        (new LiveRecordingInfo())->checkRecordId($liveId, $liveRecordId);
        //检验请求参数
        $res = $this->checkReadParam(['type' => $type, 'gid' => $gid, 'rid' => $rid, 'rid2' => $rid2, 'start_time' => $start_time, 'param' => $param_info]);
        if ($res['status'] === false)
        {
            return show(config('code.error'), $res['msg']);
        }
        if (isset($res['data']['start_date']))
        {
            $start_time = $res['data']['start_date'];
        }
        $notice = $this->notice[$type] ?? '下单前请务必核对好购买信息';
        if (!$gid)
        {
            if (isset($this->gidDefault[$type]))
            {
                $gid = $this->gidDefault[$type];
            } else
            {
                return show(config('code.error'), '未知的商品');
            }
        }
        $GoodsCacheModel = new GoodsCacheModel();
        //获取定制报告商品数据
        if ($type === 15)
        {
            $goods = (new ZlcrCustomReportGoods())->batchGetInfoByIds($gid);
            $goodsInfo = $this->resetCustomQuestionGoods($goods);
        }//版本2.9.8以后会员商品,ios用苹果支付不支持打折和优惠券
        elseif ($type === 8)
        {
            $goods = (new GoodsCacheModel())->getVipGoodsVersion((int)$this->user['id']);
            if (Util::CheckAppVersion('2.10.5') !== '小')
            {
                if (Util::IsIos())
                {
                    $tmpVipGid = 20107;
                } else
                {
                    $tmpVipGid = 154;
                }
            } else
            {
                if (Util::IsIos())
                {
                    $tmpVipGid = 20100;
                } else
                {
                    $tmpVipGid = 35;
                }
            }
            $goodsInfo = $GoodsCacheModel->resetGoodsInfo2($this, $type, $goods, $rid, $rid2, $start_time, [$tmpVipGid], ['isGoodInfo' => true, 'start_time' => $start_time, 'rid' => $rid]);
        } else//获取其他商品数据
        {
            $GoodsCacheModel = new GoodsCacheModel();
            if (GoodsCacheModel::isBaziJsjr($type, $gid))
            {
                $goods = $GoodsCacheModel->getBaziJsjrGoods($this->user['id'], $param_info['history_id'])['goods'];
                $gid = current($goods)['id'];
            } elseif ($type === 29)
            {
                $goodsInfo = (new Zl6Meditation())->goodsInfo($param_info['data_id'], $param_info['in_sign'] ?? 0);
                $gid = $goodsInfo['id'];
                $goods = [$goodsInfo];
            } elseif ($type === 17)
            {
                $goods = $GoodsCacheModel->getSynastryReportGoods($gid);
            } else
            {
                $goods = $GoodsCacheModel->GoodsTypeInfo($type);
            }
            $goods = array_column($goods, null, 'id');
            if ($type === 27)
            {
                $goods = [
                    $gid => $goods[$gid],
                ];
            }
            (new ZhunleActivity())->goodsActiveInfo($type, $goods, $start_time);
            if ($liveId)
            {
                (new LiveGoodsActivity())->getLiveOrderTypeGoods($liveId, $type, $goods, ['isCloseActive' => true]);
            }
            $goodsInfo = $GoodsCacheModel->resetGoodsInfo2($this, $type, $goods, $rid, $rid2, $start_time, [$gid], ['isGoodInfo' => true, 'start_time' => $start_time, 'rid' => $rid]);
        }
        // 神策数据打点
        if ($goods && $goodsInfo)
        {
            $goodsInfo['notice'] = $notice;
            if ($type === 35)
            {
                if ($gid === 164)
                {
                    $nameAnalyzeRecord = (new Zl9NameAnalyzeRecord())->getInfoById($param_info['history_id'], ['surname', 'name', 'rid']);
                    $recode = (new Recode())->getInfoById($nameAnalyzeRecord['rid']);
                    $des = '开通档案：' . $recode['name'];
                    $des2 = '名字：' . $nameAnalyzeRecord['surname'] . $nameAnalyzeRecord['name'];
                } else
                {
                    $nameAnalyzeRecord = (new Zl9NameAnalyzeCreateNameRecord())->getInfoById($param_info['history_id'], ['type', 'params']);
                    if ($gid === 165)
                    {
                        $des = '开通档案：' . $nameAnalyzeRecord['params']['recode_name'];
                    } else
                    {
                        $des = '开通档案：' . implode('、', array_column($nameAnalyzeRecord['params']['originator_data'], 'name'));
                    }
                    $des2 = '';
                }
                foreach ($goodsInfo['goods_data'] as $key => $datum)
                {
                    $datum['des'] = $des;
                    $datum['des2'] = $des2;
                    $goodsInfo['goods_data'][$key] = $datum;
                }
            }
            $goodsInfo['goods_data'] = array_values($goodsInfo['goods_data']);
            if (isset($goodsInfo['coupon_data']['data']))
            {
                unset($goodsInfo['coupon_data']['data']);
            }
            $goodsInfo['apple_pay_active_icon'] = Env::get('host.photo') . '/app/test/apple_pay_active_icon.png';
            return show(config('code.success'), '获取成功', $goodsInfo);
        }
        return show(config('code.error'), '商品不存在');
    }

    /**
     * 重组定制报告商品数据
     * @param $goods
     * @return array
     * @throws Exception
     */
    private function resetCustomQuestionGoods($goods)
    {
        $gid = current(array_keys($goods));
        $goods = current($goods);
        $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);  // 账户信息

        // 查询是否开启折扣活动，获取折扣信息
        $activeData = null;
        // 定制报告商品不支持VIP内部价格，所以不需要查询vip信息
        $activing = (new ZhunleActivity())->getActivingGood(15, $gid);

        /**
         * 新版活动结构
         */
        if ($activing)
        {
            $nowPrice = $goods['price'] * sprintf('%.2f', $activing['attr']);
            $activeData2['name'] = $activing['name'];
            $activeData2['discount_price'] = $goods['price'] - $nowPrice;
            $activeData2['now_price'] = $nowPrice;
            $activeData2['type'] = 1;
        }

        if ($activing)
        {
            $activeData['name'] = $activing['name'];
            $activeData['discount'] = sprintf('%.2f', $activing['attr']);
        }

        return [
            'goods_data' => [
                0 => [
                    'gid' => $gid,
                    'name' => $goods['question_name'],
                    'des' => '',
                    'price' => $goods['price'],
                    'active_data' => $activeData2 ?? null,
                ],
            ],
            'active_data' => $activeData,
            'coupon_data' => [
                'usable_num' => 0,
                'name' => '优惠券',
            ],
            'has_mobile' => 1,// TODO 暂时关闭下单验证手机号逻辑
            'coin_pwd_status' => (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0,  // 是否设置了支付密码
            'coin_num' => (int)($user_coin['balance'] ?? 0),// 准币余额
            'pay_pop_tips' => $this->pay_pop_tips,
        ];
    }

    /**
     * 检测获取商品信息接口请求参数是否正确
     * @param $param
     * @return array
     * @throws ApiException
     */
    private function checkReadParam($param)
    {
        $result = [
            'status' => true,
            'msg' => '',
        ];
        switch (true)
        {
            case !in_array($param['type'], [1, 2, 3, 4, 5, 6, 7, 8, 15, 16, 17, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35], true):
                return [
                    'status' => false,
                    'msg' => '未知的商品',
                ];
            case  in_array($param['type'], [6, 15, 16, 17, 22, 23, 24, 25, 26, 27, 35], true) && !$param['gid']:
                return [
                    'status' => false,
                    'msg' => '缺少商品参数',
                ];
            case in_array($param['type'], [5, 7, 23, 26, 27, 28], true) && !$param['rid']:
                return [
                    'status' => false,
                    'msg' => '档案未知',
                ];
        }
        if (!$param['start_time'] && (in_array($param['type'], [2, 3, 4, 12, 17], true) || $param['gid'] === 91))
        {
            return [
                'status' => false,
                'msg' => '请选择开始时间',
            ];
        }
        //检验时间格式
        if ($param['start_time'])
        {
            $res = Util::FormatFortuneTime($param['type'], $param['start_time']);
            $param['start_time'] = $res['start_date'];
            $result['data']['start_date'] = $res['start_date'];
        }
        if ((!$param['rid'] || !$param['rid2']) && in_array($param['type'], [17, 25]))
        {
            return [
                'status' => false,
                'msg' => '服务异常，请稍后重试～',
            ];
        }
        if ($param['type'] === 35 && empty($param['param']['history_id']))
        {
            return [
                'status' => false,
                'msg' => '服务异常，请稍后重试～',
            ];
        }
        if ($param['type'] === 28 && empty($param['param']['history_id']) && !$param['gid'])
        {
            return [
                'status' => false,
                'msg' => '服务异常，请稍后重试～',
            ];
        }
        return $result;
    }
}
